<template>
  <div id="insidePopup">
    <el-dialog
      title="提示窗口"
      :visible.sync="dialogVisible"
      width="80vw"
      height="80vh"
      :before-close="handleClose"
      class="outWindow"
    >
      <div class="container">
        <!-- City -->
        <div class="city">
          <div class="title">
            <h2>{{ city.name }}</h2>
            <h3>{{ city.province }}</h3>
          </div>
          <div class="date-time">
            <div class="dmy">
              <div id="txt">{{ nowTime }}</div>
              <div class="date">
                {{ dateStr }}
              </div>
            </div>
            <div class="temperature">
              <p>{{ lives.temperature }}°<span>C</span></p>
            </div>
            <div class="clear"></div>
          </div>
        </div>
        <div class="forecast">
          <div class="forecast-icon">
            <img
              src="../../assets/img/forecast.png"
              alt="New York Weather Widget"
            />
          </div>
          <div class="today-weather">
            <h3>Weather</h3>
            <ul>
              <li v-for="(item, index) in listByDay.slice(0, 4)" :key="index">
                {{ item.date }}
                <span>{{ item.nighttemp }}°C-{{ item.daytemp }}°C</span>
              </li>
            </ul>
          </div>
        </div>
        <div class="clear"></div>
      </div>

      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogVisible = false" size="mini">取 消</el-button> -->
        <!-- <el-button type="primary" @click="dialogVisible = false" size="mini">确 定</el-button> -->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import qs from 'qs'

export default {
  name: 'insidePopup',
  components: { qs },
  props: {
    dialogVisible: Boolean,
    weatherData: Object
  },
  data () {
    return {
      // dialogVisible: false,
      dayarray: [
        '星期日',
        '星期一',
        '星期二',
        '星期三',
        '星期四',
        '星期五',
        '星期六'
      ],
      montharray: [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December'
      ],
      city: { code: '', name: '', province: '' },
      nowTime: '',
      inputData: '',
      lives: {
        province: '北京',
        city: '北京市',
        adcode: '110000',
        weather: '阴',
        temperature: '23',
        winddirection: '东北',
        windpower: '≤3',
        humidity: '84',
        reporttime: '2021-06-15 07:33:58'
      },
      redata: {
        status: '1',
        count: '1',
        info: 'OK',
        infocode: '10000'
      },
      forecasts: {
        city: '北京市',
        adcode: '110000',
        province: '北京',
        reporttime: '2021-06-15 07:33:58',
        casts: [
          {
            date: '2021-06-15',
            week: '2',
            dayweather: '多云',
            nightweather: '阴',
            daytemp: '32',
            nighttemp: '21',
            daywind: '南',
            nightwind: '南',
            daypower: '≤3',
            nightpower: '≤3'
          },
          {
            date: '2021-06-16',
            week: '3',
            dayweather: '小雨',
            nightweather: '小雨',
            daytemp: '27',
            nighttemp: '21',
            daywind: '西',
            nightwind: '西',
            daypower: '≤3',
            nightpower: '≤3'
          },
          {
            date: '2021-06-17',
            week: '4',
            dayweather: '晴',
            nightweather: '晴',
            daytemp: '31',
            nighttemp: '21',
            daywind: '北',
            nightwind: '北',
            daypower: '4',
            nightpower: '4'
          },
          {
            date: '2021-06-18',
            week: '5',
            dayweather: '晴',
            nightweather: '晴',
            daytemp: '34',
            nighttemp: '20',
            daywind: '西北',
            nightwind: '西北',
            daypower: '≤3',
            nightpower: '≤3'
          }
        ]
      },
      listByDay: [
        {
          date: '',
          nighttemp: '',
          daytemp: ''
        }
      ]
    }
  },
  created: function () {
    // this.initData()
  },
  watch: {
    dialogVisible: function (val) {
      this.$emit('func', this.dialogVisible)
    },
    weatherData: function (val) {
      this.city.name = this.weatherData.city
      this.getCityCode()
      setTimeout(() => {
        this.onGetDataLives()
      }, '200')
      setTimeout(() => {
        this.onGetData()
      }, '200')
    },
    lives: function (val) {
      this.$emit('weather', val)
    }
  },
  mounted: function () {
    // this.initData()
    this.city.name = this.weatherData.city
    this.getCityCode()
    setTimeout(() => {
      this.onGetDataLives()
    }, '200')
    setTimeout(() => {
      this.onGetData()
    }, '200')
    let date = new Date()
    this.time = parseInt(date.getTime() / 1000) + date.getTimezoneOffset() * 60
    this.dealWeather()
    // setTimeout(() => {
    //   this.onGetData()
    // }, '1000')
    this.timer = setInterval(() => {
      this.nowTime = this.startTime()
    })
  },
  methods: {
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    checkTime (i) {
      if (i < 10) {
        i = '0' + i
      } // add zero in front of numbers < 10
      return i
    },
    startTime () {
      let today = new Date()
      let h = today.getHours()
      let m = today.getMinutes()
      let s = today.getSeconds()
      m = this.checkTime(m)
      s = this.checkTime(s)
      let timeStr = h + ':' + m + ':' + s
      return timeStr
    },
    // --weather action--
    getWeatherData () {
      // if (this.weatherData.city === this.city.name)
      // let res = this.$store.state.app.weather
      // this.weatherData = res[0].data
      // console.log(this.weatherData.data)
      // this.listByDay = result
    },
    dealWeather () {
      let result = JSON.stringify(this.forecasts.casts)
      result = JSON.parse(result)
      // for (let i = 0; i < result.length; i++) {
      // }
      this.listByDay = result
    },
    onGetData () {
      // let url = 'http://t.weather.itboy.net/api/weather/city/'
      // 天气预报API
      let url = 'https://restapi.amap.com/v3/weather/weatherInfo?'
      let params = {
        key: '142566f6064108a30b1e26b72cc901a2',
        city: this.city.code,
        extensions: 'all'
        // output: 'JSON'
      }
      this.$axios.get(url + qs.stringify(params)).then(res => {
        if (res) {
          this.redata = res.data
          if (res.data.forecasts[0]) this.forecasts = res.data.forecasts[0]
          console.log(this.redata)
          // this.$store.dispatch('setWeather', [
          //   { cityCode: this.city.code, data: res.data }
          // ])
        }
      })
    },
    onGetDataLives () {
      // let url = 'http://t.weather.itboy.net/api/weather/city/'
      // 天气预报API
      let url = 'https://restapi.amap.com/v3/weather/weatherInfo?'
      let params = {
        key: '142566f6064108a30b1e26b72cc901a2',
        city: this.city.code,
        extensions: 'base'
        // output: 'JSON'
      }
      this.$axios.get(url + qs.stringify(params)).then(res => {
        if (res) {
          this.redata.lives = res.data.lives
          if (res.data.lives[0]) this.lives = res.data.lives[0]
          // this.$store.dispatch('setWeather', [
          //   { cityCode: this.city.code, data: res.data }
          // ])
        }
      })
    },

    // 此处已改为使用高德API
    getCityCode () {
      // let url = 'http://localhost:8444/city_code?' + 'city='
      let url = 'https://restapi.amap.com/v3/geocode/geo?'
      // let parems = this.city.name
      let params = {
        key: '142566f6064108a30b1e26b72cc901a2',
        address: this.city.name
      }
      this.$axios.get(url + qs.stringify(params)).then(res => {
        if (res) {
          let result = res.data
          // this.city.code = result.dataStr[1]
          // this.city.name = result.dataStr[0]
          this.city.name = result.geocodes[0].city
          this.city.province = result.geocodes[0].province
          this.city.code = result.geocodes[0].adcode
          console.log(this.city)
          this.reloadOfPart()
        }
      })
    },
    async getIpPosition () {
      let params = {
        key: '142566f6064108a30b1e26b72cc901a2'
      }
      let result = await new Promise((resolve, reject) => {
        this.$axios
          .get('https://restapi.amap.com/v3/ip?' + qs.stringify(params)) // 高德地图IP查询API
          .then(res => {
            if (res) {
              // let result = res.data.city
              resolve(res.data)
            }
          })
          .catch(error => {
            console.log(error)
          })
      })
      this.city.name = result.city
        .slice(0, result.city.length - 1)
        .split(' ')[0] // 仅为简单处理
      console.log(result.city.slice(0, result.city.length - 1).split(' ')[0])
      this.city.province = result.province
    },
    // --utils fuctions--
    async initData () {
      await this.getIpPosition().then(() => {
        console.log(this.city)
        this.inputData = this.city.name
        this.getCityCode()
      })
    },
    reloadOfPart () {
      this.reloadFlag = false
      this.$nextTick(() => {
        this.reloadFlag = true
      })
    }
  },
  computed: {
    dateStr: function () {
      let mydate = new Date()
      let year = mydate.getYear()
      if (year < 1000) year += 1900
      let day = mydate.getDay()
      let month = mydate.getMonth()
      let daym = mydate.getDate()
      if (daym < 10) daym = '0' + daym
      let dateStr =
        '' +
        this.dayarray[day] +
        ', ' +
        this.montharray[month] +
        ' ' +
        daym +
        ', ' +
        year +
        ''
      return dateStr
    }
    // listByDay: function () {
    //   let result = JSON.stringify(this.weatherData[0].data.data.forecast)
    //   result = JSON.parse(result)
    //   console.log(typeof result[0].low)
    //   for (let x in result) {
    //     x.low = x.low.replace('低温 ', '')
    //     x.high = x.high.replace('高温 ', '')
    //   }
    //   return result
    // }
  },
  beforeDestroy: function () {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../assets/css/style.css';
@import url('http://fonts.useso.com/css?family=Oxygen:400,300,700');
@import url('http://fonts.useso.com/css?family=Open+Sans:400,600,700');
@import url('http://fonts.useso.com/css?family=Raleway:100,200');
#insidePopup {
  font: inherit;
  div {
    display: block;
  }
  ol,
  ul {
    list-style: none;
    padding: 0;
    margin: 0;
  }
  blockquote,
  q {
    quotes: none;
  }
  blockquote:before,
  blockquote:after,
  q:before,
  q:after {
    content: '';
    content: none;
  }
  table {
    border-collapse: collapse;
    border-spacing: 0;
  }
  /* start editing from here */
  a {
    text-decoration: none;
  }
  .txt-rt {
    text-align: right;
  } /* text align right */
  .txt-lt {
    text-align: left;
  } /* text align left */
  .txt-center {
    text-align: center;
  } /* text align center */
  .float-rt {
    float: right;
  } /* float right */
  .float-lt {
    float: left;
  } /* float left */
  .clear {
    clear: both;
  } /* clear float */
  .pos-relative {
    position: relative;
  } /* Position Relative */
  .pos-absolute {
    position: absolute;
  } /* Position Absolute */
  .vertical-base {
    vertical-align: baseline;
  } /* vertical align baseline */
  .vertical-top {
    vertical-align: top;
  } /* vertical align top */
  .underline {
    padding-bottom: 5px;
    border-bottom: 1px solid #eee;
    margin: 0 0 20px 0;
  } /* Add 5px bottom padding and a underline */
  nav.vertical ul li {
    display: block;
  } /* vertical menu */
  nav.horizontal ul li {
    display: inline-block;
  } /* horizontal menu */
  img {
    max-width: 100%;
  }
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: center;
  background-size: cover;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  font-family: 'Open Sans', sans-serif;
  text-align: center;
}
.outWinow {
  padding: 0 !important;
  a {
    transition: 0.5s all;
    -webkit-transition: 0.5s all;
    -moz-transition: 0.5s all;
    -o-transition: 0.5s all;
    -ms-transition: 0.5s all;
    text-decoration: none;
  }
}
.container {
  height: 60vh;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.73);
  background-image: url('../../assets/img/background.jpg');
  min-height: 300px;
  .city {
    background: url('../../assets/img/xingcheng.jpg');
    width: 60%;
    height: 100%;
    position: relative;
    float: left;
    background-repeat: no-repeat;
    background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;

    position: relative;
    div#txt {
      font-size: 35px;
      font-weight: 100;
      margin-bottom: 10px;
      letter-spacing: 1px;
    }

    .dmy {
      width: 50%;
      float: left;
      text-align: left;
      padding-top: 2vh !important;
    }
    .title {
      float: right;
      font-family: 'Oxygen', sans-serif;
      padding: 30px 30px 0 0;
    }

    .title h2 {
      color: #fff;
      font-size: 30px;
    }

    .title h3 {
      font-size: 16px;
      font-weight: 600;
      color: #eee;
      margin-top: 10px;
      text-align: right;
    }

    .date-time {
      position: absolute;
      bottom: 0;
      color: #fff;
      width: 90%;
      padding: 0 30px 10px 30px;
      font-family: 'Oxygen', sans-serif;
    }
    .temperature {
      width: 50%;
      float: left;
    }

    .temperature p {
      font-family: 'Raleway', sans-serif;
      font-size: 90px;
      font-weight: 100;
      margin: 0;
    }

    .temperature p span {
      font-size: 40px;
      font-weight: 200;
    }
  }
}
.forecast {
  height: 100%;
  width: 40%;
  position: relative;
  float: right;
  overflow: hidden;
  .forecast-icon {
    margin: 25px 0;
    img {
      display: block;
      margin: 0 auto;
    }
  }

  .today-weather {
    h3 {
      text-align: center;
      font-size: 50px;
      color: #fff;
      width: 80%;
      margin: 0 auto 20px;
      padding-bottom: 10px;
      border-width: thin;
      border-bottom: 1px solid #eee;
    }
    ul {
      list-style: none;
      li {
        width: 74%;
        margin: 0 auto;
        line-height: 39px;
        border-width: thin;
        border-bottom: 1px solid #777;
        color: #eee;
        font-weight: 600;
        text-align: left;
        padding-left: 20px;
        span {
          float: right;
          padding-right: 10px;
        }
      }
      li:nth-child(5) {
        border-bottom: none;
      }
    }
  }
}
</style>
